package fishBids.group3.behaviour.common;

import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.SimpleBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;

public class FindTypeBehaviour extends SimpleBehaviour {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 8997021799920432058L;
	
	public FindTypeBehaviour(String type, Agent creatorAgent, AID typeID, long waitingMiliSeconds ){
		this.TYPE = type;
		this.creatorAgent = creatorAgent;
		this.typeID = typeID;
		this.waitingMiliSeconds = waitingMiliSeconds;
	}

	@Override
	public void action() {   

		// Creates the description for the type of agent to be searched
//		System.out.println("Finding type " + TYPE );
		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(TYPE);
		dfd.addServices(sd);

		// It finds agents of the required type
		DFAgentDescription[] res = new DFAgentDescription[1];
		try {
			res = DFService.search(myAgent, dfd);
		} catch (FIPAException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// Gets the first occurrence, if there was success
		if (res.length > 0)
		{
			AID aid = (AID)res[0].getName();
			typeID.setName (aid.getName() );
			typeID.setLocalName(aid.getLocalName());
			end = true;
		}
		else
		{
			// If no type has been found, it waits 5 seconds
			creatorAgent.doWait(5000);
		}
		
	}

	@Override
	public boolean done() {
		return end;
	}
	
	String TYPE;
	Agent creatorAgent;
	AID typeID;
	boolean end = false;
	long waitingMiliSeconds;

}
